package com.qianfeng.rencai.security.filter;

import com.qianfeng.rencai.controller.CaptchaController;
import com.qianfeng.rencai.enums.LoginErrorCode;
import com.qianfeng.rencai.exceptions.ValidateCodeException;
import com.qianfeng.rencai.security.handler.RchAuthenticationFailureHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by wenka on 2022/3/30 21:33
 *
 * @author wenkaixin
 * @version 1.0
 * @since 1.0
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    public static final String LOGIN_PATH = "/login";
    @Resource
    private RchAuthenticationFailureHandler rchAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //只有处理登录功能的时候才执行
        if(LOGIN_PATH.equals(request.getRequestURI()) && request.getMethod().equalsIgnoreCase("post")){
            try {
//                validateCode(request);
                //取出session中的验证码对象
                HttpSession session = request.getSession();
                String code = (String) session.getAttribute(CaptchaController.CAPTCHA_SESSION_KEY);
                //取出表单中的验证码信息
                String captchaRequest = request.getParameter(CaptchaController.CAPTCHA_SESSION_KEY);
                Assert.hasText(captchaRequest,()->{
                    throw new ValidateCodeException(LoginErrorCode.VALIDATE_CODE_ISNULL.getMsg(), LoginErrorCode.VALIDATE_CODE_ISNULL.getCode());
                });
                Assert.isTrue(code.equalsIgnoreCase(captchaRequest), ()->{
                    throw new ValidateCodeException(LoginErrorCode.VALIDATE_CODE_ERROR.getMsg(), LoginErrorCode.VALIDATE_CODE_ERROR.getCode());
                });
                //验证通过,清除session中的验证码
                session.removeAttribute(CaptchaController.CAPTCHA_SESSION_KEY);
            } catch (AuthenticationException e) {
                rchAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        //如果不是登录地址则放行
        filterChain.doFilter(request, response);
    }
}
